export default {
  data() {
    return {
      appShowDetail: false,
      appJson: [],
      appDetail: {}, // 详情内容
      appDefaultDetail: {}, // 默认详情内容
      appModel: this.$route.meta.appModel,
      appApi: null,
    }
  },
  computed: {
    appId() {
      return this.$route.meta.appId || 'id'
    },
  },
  created() {
    if (!this.appApi) this.appApi = this.appModel
    this.appJson = this.json

    this.appGetDetail()
  },
  methods: {
    async appGetDetail() {
      const { id } = this.$route.params

      this.appDetail = {
        ...this.detail,
        ...this.appDefaultDetail,
      }

      // 获取详情（默认数据）
      if (!id) {
        if (this.appAfterFetch) this.appAfterFetch()
        return
      }
      // 获取详情(接口)
      else {
        await this.$http(`${this.appApi}/${id}`).then((res) => {
          const detail = res

          // 处理默认值
          if (this.appDefaultDetail) {
            for (const key in this.appDefaultDetail) {
              if (detail[key] === null || detail[key] === undefined) {
                detail[key] = this.appDefaultDetail[key]
              }
            }
          }

          // 取回数据给appDetail之前
          if (this.appBeforeFetch) this.appBeforeFetch(detail)

          this.appDetail = detail

          if (this.appAfterFetch) this.appAfterFetch()
        })
      }
    },
    async appHandleSubmit(goBack = true) {
      return new Promise((resove, reject) => {
        // if (e) e.preventDefault()

        let appDetail = {
          ...this.appDetail,
          ...this.params,
        }

        this.$refs.appForm.validate(async (valid) => {
          if (valid) {
            if (this.appBeforeSubmit) {
              const reulst = await this.appBeforeSubmit(appDetail)
              if (reulst == false) {
                reject()
                return false
              }
            }

            // 提交成功后
            const onSuccess = (res) => {
              if (this.appAfterSave) this.appAfterSave(res)
              if (this.appAfterSubmit) this.appAfterSubmit(res)

              this.$message.success(appDetail[this.appId] ? '保存成功' : '添加成功')
              this.$emit('change')
              if (goBack) this.appHandleClose()
              resove(res)
            }

            if (appDetail[this.appId]) {
              this.$http
                .put(`${this.appApi}/${appDetail[this.appId]}`, appDetail, {
                  showLoading: true,
                })
                .then(onSuccess)
            } else {
              this.$http
                .post(`${this.appApi}`, appDetail, {
                  showLoading: true,
                })
                .then(onSuccess)
            }
          } else {
            reject()
            return false
          }
        })
      })
    },
    async appHandleCancel() {
      this.appHandleClose()
    },
    async appHandleClose() {
      this.$router.go(-1)
    },
  },
}
